define(function () {
	var exports = {};

	var tagCloud = require('dashboard/js/tagCloud'),
		util = require('dashboard/js/util');

	var initDataChart = {
		time : [],
		pdata : [],
		ndata : []
	},
	termFlag = true,
	nowTime = 0,
	nowMinData = [],
	preUsercount = 0;
    
    //  渲染echart
    var renderEchart = function (rdata, flag) {
        // echart初始化
        require([ 'echarts', 'echarts/chart/line' ], function (ec) {
            var myChart = ec.init(document.getElementById('mainChart')); 

            var option = {
			    tooltip : {
			        trigger: 'axis',
			    },
			    legend: {
			        data:['今日浏览量','昨日浏览量'],
			        x: 'right',
			        padding: [5,20,0,0],
			        textStyle: {
			        	color: '#818181'
			        }
			    },
			    grid: {
			    	borderWidth : '0',
			    	y: 70
			    },
			    toolbox: {
			        show : false
			    },
			    color: ['#ea6004','#213f51'],
			    calculable : true,
			    animation: false,
			    xAxis : [
			        {
			            type : 'category',
			            boundaryGap : false,
			            splitLine : {
			            	lineStyle : {
			            		color : '#242424'
			            	}
			            },
			            axisLine : {
			            	lineStyle : {
			            		color : '#424242'
			            	}
			            },
			            axisLabel : {
			            	textStyle : {
			            		color : '#7e7e7e'
			            	},
			            	interval: 59,
			            	formatter: function(value){
			            		return value.substr(0,2)+'点';
			            	}
			            },
			            data: function() {
			                var x = [];
			                for (var i = 0; i < 24; i++) {
			                	for (var j =0; j < 60; j++){
			                		var hour = i < 10 ? '0'+i.toString() : i.toString();
			                		var min = j <10 ? '0'+j.toString() : j.toString();
			                		x.push(hour+':'+min);
			                	}
			                }
			                return x;
			            }()
			        }
			    ],
			    yAxis : [
			        {
			            type : 'value',
			            axisLine : {
			            	lineStyle : {
			            		color : '#424242'
			            	}
			            },
			            axisLabel : {
			            	textStyle : {
			            		color : '#7e7e7e'
			            	}
			            },
			            splitLine : {
			            	lineStyle : {
			            		color : '#242424'
			            	}
			            },
			        }
			    ],
			    series : [
			        {
			            name:'今日浏览量',
			            type:'line',
			            smooth:true,
            			symbol:'none',
			            itemStyle: {
			            	normal: {
			            		areaStyle: {type:'default'}
			            	}
			            },
			            data:[],
			            markPoint: {
			            	data: [
			            	{
			                    name: '当前分钟浏览量',
			                    clickable: false,
			                    symbol:'pin',
			                    symbolSize:30,
		                    	xAxis : '',
		                    	yAxis : '',
			                    itemStyle:{
			                    	normal:{
			                        	color: '#0c0c0c',
			                    		borderColor: '#757575',
			                    		borderWidth: '1',
										label: {
			                    			textStyle: {fontSize:13,color:'#999999'},
			                    			formatter: function(mdata){
			                    				return ' 分钟统计 \n ' + mdata.value + ' ';
			                    			}
			                    		}
			                        },
			                        emphasis:{
			                        	borderWidth: '1',
			                        	label: { textStyle: {fontSize:13}}
			                        }
			                    }
			                },
			                {
			                	name: '当前点',
			                	symbol: 'circle', 
			                	symbolSize: 8,
                     			effect:{show:true,type:'bounce'},
                     			itemStyle:{normal:{color:'#e26d1e',borderColor:'#848484',borderWidth:4}}
			                }]
			            },
			        },
			        {
			            name:'昨日浏览量',
			            type:'line',
			            smooth:true,
            			symbol:'none',
			            itemStyle: {
			            	normal: {
			            		lineStyle:{
			                        width:1
			                    },
			            		areaStyle: {type:'default'}
			            	}
			            },
			            data:[]
			        }
			    ]
            };
    		
    		if (flag == 'init') {
    			var initNdata = [], initTime = [];
    			_.each(rdata, function(value,key){  
    				value.value && initNdata.push(value.value);
    				value.time && initTime.push(value.time);
    			})
    			initDataChart.ndata = initNdata;
    			initDataChart.time = initTime;
    			option.series[1].data = initDataChart.pdata;
				option.series[0].data = initNdata;
				option.series[0].markPoint.data[0].xAxis = util.timeToHour(initDataChart.time[initDataChart.time.length-1]);
				option.series[0].markPoint.data[0].yAxis = option.series[0].data[option.series[0].data.length-1]+6000;
				option.series[0].markPoint.data[0].value = option.series[0].data[option.series[0].data.length-1];
				option.series[0].markPoint.data[1].xAxis = util.timeToHour(initDataChart.time[initDataChart.time.length-1]);
				option.series[0].markPoint.data[1].yAxis = option.series[0].data[option.series[0].data.length-1];
    			// option.series[0].markPoint.data[1].value = option.series[0].data[option.series[0].data.length-1];
    			nowTime = initDataChart.time[initDataChart.time.length-1];
				var now = new Date();
				now.setTime(nowTime);
				$('#dataRealtime').html(now.toLocaleDateString().replace(/\//g,'-') + ' ' + now.toTimeString().substr(0,8));
    		} else {
    			option.series[1].data = initDataChart.pdata;
				option.series[0].data = initDataChart.ndata;
    			option.series[0].markPoint.data[0].xAxis = util.timeToHour(initDataChart.time[initDataChart.time.length-1]);
				option.series[0].markPoint.data[0].yAxis = option.series[0].data[option.series[0].data.length-1]+6000;
    			option.series[0].markPoint.data[1].xAxis = util.timeToHour(initDataChart.time[initDataChart.time.length-1]);
				option.series[0].markPoint.data[1].yAxis = option.series[0].data[option.series[0].data.length-1];
    			// option.series[0].markPoint.data[1].value = option.series[0].data[option.series[0].data.length-1];
    			if (flag == 'addpin') {
    				var sum = _.reduce(rdata, function(memo, num, key){ 
    					if (key > 17){
					 		return memo + num.value;
    					} else {
    						return 0;
    					}
    				}, 0);
    				option.series[0].markPoint.data[0].value = sum;
    				var now = new Date();
					now.setTime(rdata[rdata.length-1].time);
					$('#dataRealtime').html(now.toLocaleDateString().replace(/\//g,'-') + ' ' + now.toTimeString().substr(0,8));
    			} else {
    				option.series[0].markPoint.data[0].value = option.series[0].data[option.series[0].data.length-1];
    			}
    		}

            // 为echarts对象加载数据 
            myChart.setOption(option); 
        });
    }

    var dealYesterday = function (data) {
    	return _.map(data, function(value,key){ 
    		return value.value;
    	})
    }


	var init = function () {

		/* aside - tagclouds */
		$.ajax({
			type: 'post',
			url: '/dashboard/realtime/netflow/getSearchWrodTopList',
            jsonp: "callback",
            jsonpCallback:"jsonpCallback",
            dataType: "json",
            async:false,
			data:{platform:'PC',num:30},
			success: function(json){ 
				termFlag = true;
				tagCloud.init({id : "tagscloud", flag: 'init', data : json.data});
			}
		})
		
		/* aside - release number */
		$.ajax({
			type: 'post',
			url: '/dashboard/realtime/tv/info/usercount',
            jsonp: "callback",
            jsonpCallback: "jsonpCallback",
            dataType: "json",
            async:false,
			success: function(json){
				// json = json.responseText;
				var temp = _.template($('#templateRelease').text());
				$('#dataRelease').html(temp({ pdata : util.numFormat(json), ndata : util.numFormat(json)}));
				preUsercount = parseInt(json);
			} 
		})

		/* content - chart */
		$.ajax({
			type: 'post',
			url: '/dashboard/realtime/netflow/getNetFlowByMinYestoday',
            jsonp: "callback",
            jsonpCallback: "jsonpCallback",
            dataType: "json",
            data: {type:'vppv'},
            async: false,
			success: function(json){
               	// json = JSON.parse(json.responseText);
               	initDataChart.pdata = dealYesterday(json.data);
               	$.ajax({
					type: 'post',
					url: '/dashboard/realtime/netflow/getNetFlowByMin',
					jsonp: "callback",
					jsonpCallback:"jsonpCallback",
					dataType: "json",
					data:{type:'vppv'},
					async:false,
					success: function(json){ 
						renderEchart(json.data,'init');
					}
				})
            } 
		})

		/* content - table */
		$.ajax({
			type: 'post',
			url: '/dashboard/realtime/tv/info/infocount',
            jsonp: "callback",
            jsonpCallback:"jsonpCallback",
            dataType: "json",
            data: {num:4},
            async:false,
			success: function(json){
				// json = JSON.parse(json.responseText);
				var temp = _.template($('#templateTable').text());
				$('#mainTable').html(temp({ data : json, util : util}));
			}
		})
	}

	var refreshBy2 = function () {

		/* aside - release number */
		$.ajax({
			type: 'post',
			url: '/dashboard/realtime/tv/info/usercount',
            jsonp: "callback",
            jsonpCallback:"jsonpCallback",
            dataType: "json",
            async:false,
			success: function(json){
				// json = json.responseText;
				var temp = _.template($('#templateRelease').text());
				$('#dataRelease').html(temp({ pdata : util.numFormat(preUsercount), ndata : util.numFormat(json)}));
				preUsercount = parseInt(json);
			}
		})

		/* content - chart */
		var theDate = new Date();
		theDate.setTime(nowTime);
		if ( theDate.getHours() == 0 && theDate.getMinutes() == 0 && (theDate.getSeconds() == 0 || theDate.getSeconds() == 1) ) {
			initDataChart.time = [];
			initDataChart.pdata = [];
			initDataChart.ndata = [];
			$.ajax({
				type: 'post',
				url: '/dashboard/realtime/netflow/getNetFlowByMinYestoday',
	            jsonp: "callback",
	            jsonpCallback: "jsonpCallback",
	            dataType: "json",
	            data: {type:'vppv'},
	            async: false,
				success: function(json){
	               	// json = JSON.parse(json.responseText);
	               	initDataChart.pdata = dealYesterday(json.data);
	               	$.ajax({
						type: 'post',
						url: '/dashboard/realtime/netflow/getNetFlowByMin',
						jsonp: "callback",
						jsonpCallback:"jsonpCallback",
						dataType: "json",
						data:{type:'vppv'},
						async:false,
						success: function(json){ 
							renderEchart(json.data,'init');
						}
					})
	            } 
			})
		} else {
			$.ajax({
				type: 'post',
				url: '/dashboard/realtime/netflow/getHourData',
	            jsonp: "callback",
	            jsonpCallback: "jsonpCallback",
	            dataType: "json",
	            data: {type:'vppv', time: theDate.getTime()},
	            async: false,
				success: function(json){ 
					var differ = (json.data[json.data.length-1].time - theDate.getTime())/1000;
					if (differ >= 120) {
						$.ajax({
							type: 'post',
							url: '/dashboard/realtime/netflow/getNetFlowByMin',
				            jsonp: "callback",
				            jsonpCallback:"jsonpCallback",
				            dataType: "json",
				            data:{type:'vppv',time:nowTime},
				            async:false,
							success: function(data){ 
								initDataChart.time.push(data.data[data.data.length-1].time);
								initDataChart.ndata.push(data.data[data.data.length-1].value);
								renderEchart(initDataChart,'refresh');
							}
						})
						nowTime += 60000;
					} else {
						renderEchart(json.data,'addpin');
					}
				},
	            error: function(json){ }
	        })
	    }

		$.ajax({
			type: 'post',
			url: '/dashboard/realtime/tv/info/infocount',
            jsonp: "callback",
            jsonpCallback:"jsonpCallback",
            dataType: "json",
            data: {num:4},
            async:false,
			success: function(json){
				// json = JSON.parse(json.responseText);
				var temp = _.template($('#templateTable').text());
				$('#mainTable').html(temp({ data : json, util : util}));
			}
		})
	}

	var refreshBy7 = function () {
		if ( termFlag == true ) {
			/* aside - mobileTagClouds */
			$.ajax({
				type: 'post',
				url: '/dashboard/realtime/netflow/getSearchWrodTopList',
	            jsonp: "callback",
	            jsonpCallback:"jsonpCallback",
	            dataType: "json",
	            async:false,
				data:{platform:'M',num:30},
				success: function(json){
					$('.pc-title').removeClass('hightlight');
					$('.m-title').addClass('hightlight');
					tagCloud.init({id : "tagscloud", flag: 'refresh', data : json.data})();
					termFlag = false;
				}
			})
		} else {
			/* aside - mobileTagClouds */
			$.ajax({
				type: 'post',
				url: '/dashboard/realtime/netflow/getSearchWrodTopList',
	            jsonp: "callback",
	            jsonpCallback:"jsonpCallback",
	            dataType: "json",
	            async:false,
				data:{platform:'PC',num:30},
				success: function(json){
					$('.pc-title').addClass('hightlight');
					$('.m-title').removeClass('hightlight');
					// $('.hotwords-frame h3').fadeOut(500);
					// setTimeout(function(){
					// 	$('.hotwords-frame h3').text('PC热词');
					// 	$('.hotwords-frame h3').fadeIn(500);
					// },500)
					tagCloud.init({id : "tagscloud", flag: 'refresh', data : json.data})();
					termFlag = true;
				}
			})
		}
	}

	exports.render = function () {
		init();
		clearInterval(timeTicket2);
		var timeTicket2 = setInterval(refreshBy2, 2000);
		clearInterval(timeTicket7);
		var timeTicket7 = setInterval(refreshBy7, 7000);
	}
	return {
		render:function () {
			init();
			clearInterval(timeTicket2);
			var timeTicket2 = setInterval(refreshBy2, 2000);
			clearInterval(timeTicket7);
			var timeTicket7 = setInterval(refreshBy7, 7000);
		}
	};
})